const express = require("express");
const app = express();
const { port } = require("./config");
const plugins = require("./plugins/index");
const middleWare = require("./middleware");
const db = require("./dao");
/**
 *
 * 公共系统初始化
 * 配置中间件
 */
// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));
middleWare(app);
db(app);

app.get("/", (req, res) => {
  res.send("hello wrold!");
});

app.get(
  "/example",
  function (req, res, next) {
    console.log("the response will be sent by the next function ...");
    next();
  },
  function (req, res) {
    res.send("Hello from B!");
  }
);

app.listen(port, () => {
  console.log(`服务已经启动，监听地址为 http://localhost:${port}/`);
});

plugins(app);

/**
 *
 * 统一处理无响应
 *
 */
// 如果没有路径处理就返回 Not Found
app.use(function (req, res, next) {
  res.status(404).send("404 找不到指定页面");
});

// 处理错误级别的中间件
app.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    return res.send({
      status: 401,
      message: "无效的token",
    });
  }

  res.send({
    status: 500,
    message: err.message,
  });
});
